import { HttpException, Injectable } from '@nestjs/common';
import { Permission } from './entities/permission.entity';
import { User } from './entities/user.entity';
import { Role } from './entities/role.entity';
import { EntityManager, In } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class UserService {
  constructor(
    private readonly entityManager: EntityManager,
    private readonly jwtService: JwtService,
  ) {}
  async initData() {
    const user1 = new User();
    user1.username = 'xiaosong1';
    user1.password = '123123';

    const user2 = new User();
    user2.username = 'xiaosong2';
    user2.password = '123123';

    const role1 = new Role();
    role1.name = 'admin';
    role1.description = 'admin';

    const role2 = new Role();
    role2.name = 'user';
    role2.description = 'user';

    const permission1 = new Permission();
    permission1.name = 'add';
    permission1.description = 'add';

    const permission2 = new Permission();
    permission2.name = 'updata';
    permission2.description = 'updata';

    const permission3 = new Permission();
    permission3.name = 'del';
    permission3.description = 'del';

    const permission4 = new Permission();
    permission4.name = 'query';
    permission4.description = 'query';

    role1.permissions = [permission1, permission2, permission3, permission4];

    role2.permissions = [permission1, permission2, permission4];

    user1.roles = [role1];

    user2.roles = [role2];

    await this.entityManager.save(Permission, [
      permission1,
      permission2,
      permission3,
      permission4,
    ]);

    await this.entityManager.save(Role, [role1, role2]);

    await this.entityManager.save(User, [user1, user2]);
  }

  async login(createUserDto: CreateUserDto) {
    const userInfo = await this.entityManager.findOne(User, {
      where: {
        username: createUserDto.username,
        password: createUserDto.password,
      },
      relations: {
        roles: true,
      },
    });

    if (!userInfo) throw new HttpException('用户名或密码错误', 401);

    console.log(userInfo.roles);

    return {
      token: this.jwtService.sign({
        username: userInfo.username,
        roles: userInfo.roles,
      }),
    };
  }

  async getPermissionByRoleId(roleId: number[]) {
    const res = await this.entityManager.find(Role, {
      where: {
        id: In(roleId),
      },
      relations: {
        permissions: true,
      },
    });

    const permission: string[] = [].concat(
      ...res.map((item) => {
        return item.permissions.map((item) => {
          return item.name;
        });
      }),
    );

    return permission;
  }
}
